package StudyCode.summary.mycollection;

import java.util.Iterator;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GetsEitherTheOnlyElementOrTheDefaultOneInIterable {
	public static <T> T unique(Iterable<T> source, T defaultElement) {
		T element = defaultElement;

		if (source != null) {
			Iterator<T> i = source.iterator();

			if (i.hasNext()) {
				element = i.next();

				if (i.hasNext()) {
					throw new IllegalStateException("Element not unique!");
				}
			}
		}

		return element;
	}
}
